<?php
require_once("modules/config.class.php");
require_once("modules/cache.class.php");
require_once("modules/html.class.php");

/**
 * Theme object
 * containing all information for a theme.
 * @author Frédéric Delorme<frederic.delorme@gmail.com>
 * @version 1.0 - 20091218
 */
class Theme
{
	public $name;
	public $description;
	public $author;
	public $version;
	public $createdAt;
	public $path;
	#	internal variables
	
	#	Constructor
	function __construct($init){
		$this->name = $init['name'];
		$this->description = $init['description'];
		$this->author = $init['author'];
		$this->version = $init['version'];
		$this->createdAt = $init['createdAt'];
		$this->path = $init['path'];
	}
}

/*
 * Themes management 
 * @author Frédéric Delorme.
 * @version 1.0 - 20091209
 */
class Themes{
	static private $_instance = null;
	/*
	 * Liste of available themes 
	 */
	private $themesList	= array();
	private $cssLibs	= array();
	private $jsLibs		= array();
	/*
	 * Id of selected theme.
	 */
	private $selectedTheme="";
	/**
	 * Rendering buffer.
	 * @var unknown_type
	 */
	private $outputBuffer="";
	/**
	 * cache manager
	 * @var unknown_type
	 */
	private $cache = null;
	
	/*
	 * Build List of themes
	 */
	function __construct($cache){
		$root = dirname($_SERVER['SCRIPT_FILENAME'])."/themes";
		$config=Config::getInstance();
		$this->cache=$cache;
		$this->loadConfig($root,$config);
		if(isset($_REQUEST['theme'])){
			$this->setTheme($_REQUEST['theme']);
			__info(__FILE__,__LINE__,"theme is changed to selected value :".$_REQUEST['theme']);
		}else if(isset($_SESSION['theme'])){
			$this->setTheme($_SESSION['theme']);
			__info(__FILE__,__LINE__,"theme is set from session saved value :".$_SESSION['theme']);
		}else{
			$theme = $config->get("theme","name","default");
			$this->setTheme($theme);			
			__info(__FILE__,__LINE__,"theme is loaded with default");
		}
	}
	/**
	 * Loading theme Configuration from <code>system.ini</code> and load list of theme into <code>themesList</code> attribute.
	 * @param $root root of themes defintions.
	 */
	private function loadConfig($root,$config){
		//if(!isset($this->themesList) && count($this->themesList)>0){
			$path=opendir($root);
			while($filetheme=readdir($path)){
				if($filetheme!="." && 
				   $filetheme!=".." &&
				   is_dir($root."/$filetheme/") &&
				   file_exists($root."/$filetheme/theme.ini")){
					if(!isset($this->themesList[$filetheme])){
						$themeinfo=parse_ini_file($root."/$filetheme/theme.ini");
						$themeinfo = array_merge($themeinfo,array('path'=>"themes/".$filetheme));
						$otheme = new Theme($themeinfo);
						$this->themesList[$filetheme]=$otheme;
					}
				}
			}
			$this->cssLibs=$config->getGroup("csslib");
			$this->jsLibs=$config->getGroup("jslib");
			__debug(__FILE__,__LINE__,"themes::loadConfig() - csslibs: ".print_r($this->cssLibs,true));
			__debug(__FILE__,__LINE__,"themes::loadConfig() - jslibs: ".print_r($this->jsLibs,true));
		//}
		
	} 
	
	/**
	 * Return the list of themes
	 */
	function getThemes(){
		return $this->themesList;
	}
	/**
	 * is there only one theme ?
	 */
	function onlyOneTheme(){
		return (count($this->themesList)==1);
	}
	/**
	 * Set theme to the <code>id</code>theme.
	 */
	function setTheme($id){
		if(array_key_exists($id,$this->themesList)){
			$this->selectedTheme=$id;
			// save in session the selected theme.
			$_SESSION['theme'] = $id;
		}
	}
	/**
	 * return the theme named $id.
	 */
	function getTheme($id){
		return $this->themesList[$id];
	}
	/**
	 * return the actual selected theme.
	 */
	function getSelectedTheme(){

		if(isset($_REQUEST['theme'])){
			$theme = $this->themesList[$_REQUEST['theme']];
		}else if(isset($_SESSION['theme'])){
			$theme = $this->themesList[$_SESSION['theme']];
		}else{
			$config=Config::getInstance();
			$themeid = $config->get("theme","name","default");
			$theme = $this->themesList[$themeid];
		}		
		return $theme;
	}

	/**
	 * return a string containing html form with theme selector.
	 * @param $label Label on front of the theme selector.
	 * @param $title title to be displayed on mouseover.
	 * @param $addForm boolean flag indicate if a form tag must be generated.
	 * @param $addSpan boolean flag indicate if a span tag must be generated around theme selector.
	 */
	function themeSelector($label="",$title="",$accesskey="",$addForm=false,$addSpan=false){
		$html="";
		
		if($addForm){
			$html.="<form name=\"theme\" action=\"index.php\">";
		}
		if($addSpan){
			$html.="<span class=\"theme-selector\">";
		}
		if($label!=""){
			$html.="<label for=\"theme\">$label</label>&nbsp;";
		}
		$html.="<select name=\"theme\" id=\"theme\" onchange=\"submit();\" title=\"".
				($title!=""?$title:"Choose your prefered site theme").
				($accesskey!=" accesskey=\"".$accesskey."\" "?"":"")."\">";
		foreach($this->getThemes() as $key=>$theme) :
			$html.="<option value=\"".$key."\"".($key==$this->selectedTheme?" selected=\"selected\"":"")." title=\"".$theme->description."\">".
					$theme->name.
					"&nbsp;&nbsp;</option>";
		endforeach;
		$html.="</select>";
		if($addSpan){
			$html.="</span>";
		}		
		if($addForm){
			$html.="</form>";
		}
		return $html;
	}
	
	
	/**
	 * Display the <code>$template</code>.
	 * @param $template the template to be displayed. by default, index is displayed if no value is set.
	 */
	function display($template='index'){
		$theme=$this->getSelectedTheme();
		$this->outputBuffer = "";

		if(file_exists($theme->path."/".$template.".tpl")){
			$mytemplate = $theme->path."/".$template.".tpl";
		}else{
			$mytemplate = "pages/".$template.".tpl";
		}

		if($this->cache!=null){
				$buffer=$this->cache->start($mytemplate.$_SERVER['QUERY_STRING']);
			__debug(__FILE__,__LINE__,"buffer=false: ?".($buffer==false));
			if($buffer==false){
				$this->generatePage($theme, $template);
				$this->cache->register($this->outputBuffer);
				$this->cache->end();
			}else{
				$this->outputBuffer=$buffer;
			}
		}else{
			$this->generatePage($theme, $template);
		}
	}

	/**
	 * Generate the <code>$template</code> page from <code>$theme</code>.
	 * @param $theme theme where to find the template.
	 * @param $template template to be rendered.
	 */
	public function generatePage($theme, $template){
		ob_start();
		print("<?xml version=\"1.0\"? encode=\"utf-8\">\r\n");
		if(file_exists($theme->path."/".$template.".tpl")){
			__debug(__FILE__,__LINE__,"Theme::generatePage() - Theme (".$theme->name.") modified template for ".$template);
			include($theme->path."/".$template.".tpl");
		}else{
			__debug(__FILE__,__LINE__,"Theme::generatePage() - Standard template for ".$template);
			include("pages/".$template.".tpl");
		}
		$this->outputBuffer = ob_get_contents();
		ob_end_clean();
	}
	
	/**
	 * render prepared page.
	 */
	public function render(){
		echo $this->outputBuffer;
	}
	
	public function getJsLibs(){
		return $this->jsLibs;
	}
	public function getCssLibs(){
		return $this->cssLibs;
	}
	
	/**
	 * return the static instance of the THeme Manager.
	 * create the instance if does not already exist.
	 */
	function getInstance($cache=null){
		if(!isset(self::$_instance)){
			self::$_instance = new Themes($cache);
		}
		return self::$_instance;
	}
}
/**
 * Generate Css import
 * @return HTML generated
 */
function __CSSLIBS(){
	$themes = Themes::getInstance();
	$html="";
	foreach($themes->getCssLibs() as $key=>$csslib){
		$css = split(":",$csslib);
		$html .= "<link rel=\"stylesheet\" name=\"".$key."\" type=\"text/css\" href=\"".$css[1]."\" media=\"".$css[0]."\" charset=\"utf-8\" />"; 
	}
	__debug(__FILE__,__LINE__,"generate CSS libs HTML import");
	return $html;
}
/**
 * Generate JS script import
 * @return HTML generated.
 */
function __JSLIBS(){
	$html="";
	$themes = Themes::getInstance();
	foreach($themes->getJsLibs() as $js){
		$html .= "<script type=\"text/javascript\" src=\"".$js."\"></script>"; 
	}
	__debug(__FILE__,__LINE__,"generate JS libs HTML import");
	return $html;
}
?>